import React, { useState, useEffect } from 'react'
import * as Icon from '@ant-design/icons'
import { useNavigate, useLocation } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { Layout, Menu } from 'antd'
import { selectMenuList } from '../../store/reducers/tab'

const { Sider } = Layout

// 动态获取icon
const iconToElement = name => {
  return React.createElement(Icon[name])
}

function CommonSider({ collapsed }) {
  // 路由跳转
  const navigate = useNavigate()

  //获取路由路径
  const location = useLocation()

  // 使用action
  const dispatch = useDispatch()

  // 获取store的menu
  const menu = useSelector(state => state.tab.menu)

  // 处理菜单数据
  const item = menu.map(item => {
    // 无子菜单
    const child = {
      key: item.path,
      icon: iconToElement(item.icon),
      label: item.label
    }

    // 有子菜单
    if (item.children) {
      child.children = item.children.map(item => {
        return {
          key: item.path,
          icon: iconToElement(item.icon),
          label: item.label
        }
      })
    }

    return child
  })

  // 添加数据到store
  const setTabList = val => {
    dispatch(selectMenuList(val))
  }

  // 菜单切换
  const selectMenu = e => {
    let data
    menu.forEach(item => {
      if (item.path === e.keyPath[e.keyPath.length - 1]) {
        data = item
        // 如果有子菜单
        if (e.keyPath.length > 1) {
          data = item.children.find(child => {
            return child.path == e.key
          })
        }
      }
    })

    setTabList({
      path: data.path,
      name: data.name,
      label: data.label
    })
    navigate(e.key)
  }

  return (
    <Sider trigger={null} collapsed={collapsed}>
      <h3 className="app-name">{collapsed ? '广工' : '广工创新创业管理'}</h3>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={location.pathname}
        // openKeys={}
        items={item}
        style={{ height: '100%' }}
        onClick={selectMenu}
      />
    </Sider>
  )
}

export default CommonSider
